<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
    <% include ../partial/meta %>
    <link rel="stylesheet" href="/app/static/weixin/css/pure-min.css">
    <link rel="stylesheet" href="/app/static/weixin/css/weixin.css">
    <link rel="stylesheet" href="/app/static/weixin/css/plugin.css">
    <style>
    	.checkpoint-overlay {
    	    position: absolute;
    	    white-space: nowrap;
    	    line-height: 25px;
    	    margin-left: -9px; 
    	    font-size: 12px;
    	}
    	.checkpoint-overlay::before {
    	    position: absolute;
    	    content: " ";
    	    display: table;
    	    width: 23px;
    	    height: 25px;
    	    background: url(/app/static/weixin/img/location.png) 0 0 no-repeat;
    	}
    	.checkpoint-overlay-label {
    	    margin-left: 16px;
    	}
    </style>
</head>
<body class="main-list">
	<header class="header">
		<a href="javascript:history.go(-1)" class="back"><img src="/app/static/weixin/img/back.png" alt="back" ></a>
		<p>房源详情</p>
	</header>
	<div class ="main-carousel">
		<div class="carousel">
		    
		</div>
	</div> 
	<div class ="app-down-mask">
	<div class ="app-down">
		<div class="pure-g">
			<div class="pure-u-1">欢迎使用房妈妈合租平台</div>

		    <div class="pure-u-1-2 related"><a href="tel:0592-5931112">联系看房</a></div>

		    <div class="pure-u-1-2" name="down"><a href="http://a.app.qq.com/o/simple.jsp?pkgname=com.fangmm.housemother">下载房妈妈App</a></div>
		</div>
	</div>
</body>
<script src="/app/static/weixin/js/zepto.min.js"></script>
<script src="/app/static/weixin/js/pubsub.js"></script>
<script src="/app/static/weixin/js/carousel.js"></script>
<script src="/app/static/weixin/js/template.js"></script>
<script>
	// handle compatibility
	if (!Array.prototype.filter) {
	    Array.prototype.filter = function(callback) {
	      	var len = this.length;
	      	if(typeof callback != "function") {
	          	throw new TypeError();
	      	}
	      	var newArr = new Array();
	      	var thisArg = arguments[1];
	      	for(var i = 0; i < len; i++) {
	          	if(i in this) {
	              	if(callback.call(thisArg, this[i], i, this)) {
	                  	newArr.push(val);
	              	}
	          	}
	      	}
	      	return newArr;
	  	}
	}
	if (!Array.prototype.forEach) {
	    Array.prototype.forEach = function forEach(callback) {
	        var len = this.length;
	        if (typeof callback != "function") {
	            throw new TypeError();
	        }
	        var thisArg = arguments[1];
	        for (var i = 0; i < len; i++) {
	            if (i in this) {
	                callback.call(thisArg, this[i], i, this);
	            }
	        }
	    }
	}
</script>
<script id="item" type="text/html">
	<div class="thumb-carousel">
		<div class="pure-g">
			<div class="pure-u-1-4 thumb-item current">
				<div>
				整套</br>{{area}}㎡
				</div>
			</div>
			{{each rooms as room i}}
		    <div class="pure-u-1-4 thumb-item">
		    <div>{{room.roomType}}</br>{{room.area}}㎡</div>
		    </div>
			{{/each}}
		</div>
	</div>
</script>
<script id="detail" type="text/html">
	<div class="main-detail">
		<div class="pure-g">
		    <div class="pure-u-1 main-descption">
		    	<p class="whitespace nowrap">{{community}}
		    	<span class="quanjing brand-color">
		    		<a href="/app/client/panoramic/<%= listId %>">
		    		<img src="/app/static/weixin/img/full-view.png"/>全景看房
		    		</a>
		    	</span>
		    	</p>
				<p class="whitespace nowrap">¥{{singleRentFloor}}间 <small>起(整租¥{{rent}})</small></p>
		    	<p class="whitespace nowrap">{{region}} - {{roomNum}}室{{hallNum}}厅{{toiletNum}}卫 - {{area}}㎡ | 入住时间：{{checkinTime}}</p>
		    	
		    	<p class="whitespace nowrap">
		    	{{if check }}
		    		<span class="check-for">验</span>
		    	{{/if }}
		    	<span class="come-from">来源</span><span class="come-to">{{from}}</span>
		    	</p>
		    </div>
		    <div class="pure-u-1-1 comment">{{comment}}</div>
		</div>	
	</div>
</script>
<script id="room" type="text/html">
	<div class ="main-mess">
		<div class="pure-g">
			<div class="pure-u-1 sub-item">房源信息</div>
		</div>
		<div class="pure-g text-small">
		    <div class="pure-u-7-8">房源编号：{{sourceNo}}</div>
		    <div class="pure-u-1-3">朝向：{{orientation}}</div>
		    <div class="pure-u-1-3">楼层：{{floorSection}}/{{floorTotal}}</div>
		    <div class="pure-u-1-3">卫生间：{{toiletNum}}卫</div>
		    <div class="pure-u-1-3">年代：{{decade}}</div>
		    <div class="pure-u-1-3">装修：{{style}}</div>
		    <div class="pure-u-1-3">付款方式：{{paymode}}</div>
		    {{each rooms as room}}
		    <div class="pure-u-1 text-parallel">
		    	<span>{{room.roomType}} 面积：{{room.area}} 设施：
		    		{{each room.facilities as facilitie i}}
		    			{{if facilitie.count && i>0}}
		    				|{{facilitie.name}}
		    			{{else if facilitie.count && i==0}}
		    				{{facilitie.name}}
		    			{{/if}}
		    		
		    		{{/each}}
		    	<span/>
		    </div>
			{{/each}}
		</div>
	</div>
	<div class ="main-facility">
		<div class="pure-g">
			<div class="pure-u-1 sub-item">配套信息</div>
		</div>
		<div class="pure-g">
		{{each facilities as facilitie}}
			{{if facilitie.count}}
			<div class="pure-u-1-5 text-center">
				<img src="/app/static/weixin/img/selected.png"/>
				</br>{{facilitie.name}}
			</div>
			{{else}}
			<div class="pure-u-1-5 text-center">
				<img src="/app/static/weixin/img/non.png"/>
				</br>{{facilitie.name}}
			</div>
			{{/if}}
		{{/each}}
		</div>
	</div>
	<div class="main-order">
		<div class="pure-g">
			<div class="pure-u-1 sub-item">室长报价 <small>室友小组仅为报价展示及室友搭伙并未正式入住</small></div>
		</div>
		
	</div>
	<div class ="main-map">
		<div class="pure-g">
			<div class="pure-u-1 sub-item">小区地图 
			<a href="/app/client/communities/{{communityId}}" class="community-map"><img src="/app/static/weixin/img/house.png"/>小区</a>
			</div>
		</div>
		<div id ="container" style ="width:100%; height: 212px">         
		</div>
	</div>
</script>
<script id="order" type="text/html">
	<div class="pure-g sub-order">
		{{each rooms as room}}
		    <div class="pure-u-1-{{rooms.length}}">{{room.name}}</div>
		{{/each}}  
	</div>
	{{if teams.length != 0}}
		{{each teams as team i}}
			<div class="pure-g sub-order">
				<span>{{i+1}}</span>
				{{each team.seats as seat}}
			    	<div class="pure-u-1-{{rooms.length}} order-item">
			    		{{if seat.userId}}
				    		<span>
				    			<img src="{{seat.userAvatar}}">
				    			</br>
				    			{{seat.userName}}
				    		</span>
				    	{{else}}
				    		<span class="brand-color">
				    			{{seat.rent}}元/月
				    		</span>
			    		{{/if}}
		    		    	<div class="order-btn">
		    		    		{{if seat.userId && seat.leader}}
		    			    		<span class="brand-color leader">
		    			    			室长
		    			    		</span>
		    			    	{{else if seat.userId && !seat.leader}}
		    			    		<span class="roommate">
		    			    			室友
		    			    		</span>
		    			    	{{else}}
		    			    		<span class="null">
		    			    			空闲
		    			    		</span>
		    		    		{{/if}}
		    		    	</div>
			    	</div>

				{{/each}}  
			</div>
		{{/each}}
	{{else}}
		<div class="pure-g">
			<p class="text-center text-small null-tip">
			暂无室友小组，快来成为室长，创建小组吧！
			</p>
		</div>
	{{/if}}
</script>
<script id="like" type="text/html">
	<div class="main-user">
		<div class="pure-g user-like">
				<div class="pure-u-1-8">
					<span>{{data.count}}</span>
				</div>
			{{each data.users as user i}}
				{{if i< 6}}
				<div class="pure-u-1-8"><img src="{{user.userAvatar}}?q=60&w=72"/></div>
				{{/if}}
			{{/each}}
			<div class="pure-u-1-8 brand-color">
				<span>
					<img src="/app/static/weixin/img/like.png"/>
					</br>
					喜欢
				</span>
			</div>
		</div>
	</div>
	<div class="main-down">
		<div class="pure-g">
		    <div class="pure-u-1-2"><a class="ke" href="tel:0592-5931112"><img src="/app/static/weixin/img/phone.png"/>客服</a></div>
		    
		    <div class="pure-u-1-2" name="down">
		    	{{if limits && limits[0].code == 1}}
		    	<span class="zufang">我要租房</span>
		    	{{ else }}
		    	<a href="http://a.app.qq.com/o/simple.jsp?pkgname=com.fangmm.housemother">下载APP立即合租</a>
		    	{{/if}}
		    </div>
		</div>
	</div>
</script>
<script type="text/javascript" src="http://api.map.baidu.com/api?type=quick&ak=5Q3GyoZeoOi0v4ORvsfBxv8X&v=1.0"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
	$(function() {

		const api_host    = 'http://api.fangmm.com/v3';
		var house_api_url = '/houses/' + '<%= listId %>' + '?app=m';
		var favorite_api_url = '/favorites/houses/' + '<%= listId %>' + '?app=m';
		var group_api_url = '/teams/houses/' + '<%= listId %>' + '?app=m';

		var util 		  = (function() {
			return {
				getList: function(url, callback) {
					$.get(url, function(data) {
						if(0 == data.code) {
							callback(data)
						} else {
							alert(data.msg)
						}
					}, 'json')
				},
				handleNullPic: function(data) {
					data.house.rooms.filter(function(room) {
				        var bool = false;
				        data.house.images.filter(function(image) {
				            if(image.classify == room.name) {
				            	if(!room.path) {
				            		room.path = image.path
				            	}
				                bool = true;
				            }
				        })
				        if(!bool) {
				            data.house.images.push({classify: room.name, path: "http://img.fangmm.com/default.jpg"})
				            room.path = "http://img.fangmm.com/default.jpg";
				        }
				    })
				    return data
				},
				renderItem: function(str,data) {
					var html = template(str, data);
					return html
				},
				serialize: function(params) {
					var array = [];
					for (var p in params) {
					    array.push(p + '=' + params[p]);
					}
					return array.join('&');
				}

			}
		})();

		(function() {

			var $main 		  = $('.main-carousel'),
				$mainList 	  = $('.main-list'),
				$body 		  = $('body'),
				$quanjing     = $('.quanjing'),
				$mainCarousel = $('.main-carousel .carousel'),
				listData 	  = null,
				$currentIndex = $('.carousel-len .index'),
				$picLen		  = $('.carousel-len .leng'),
				picItem		  = '.thumb-item',
				mainOrder	  = '.main-order'

			util.getList(api_host + house_api_url, function(data) {
				console.log(data);
				listData = util.handleNullPic(data);
				// var img0 = listData.house.images.filter(function(img) {
				// 	return img.classify == listData.house.rooms[0].name
				// });

				function renderPic(data) {
					var html = '';
					data.forEach(function(img) {
						html += '<img src="' + img.path + '?q=60&w=480' + '" />';
					});
					return html;
				}
				
				$mainCarousel.html(renderPic(listData.house.images)).carousel({
					isShowPager:    false,
					slideCallback:  function(index) {
					    setIndex(index);
					}
				});
				var itemTpl = util.renderItem('item', listData.house)
				$main.append(itemTpl)

				function initIndexLeng(data) {
					return listData.house.images.filter(function(image) {
					    return image.classify == data.name
					})
				};
				// $picLen.text(initIndexLeng(listData.house.rooms[0]).length);

				function setIndex(index) {
					// $currentIndex.text(index + 1);
				}

				function reloadPic(data) {
					$mainCarousel.off();
					$mainCarousel.find('*').off();

					$mainCarousel.html(renderPic(data)).carousel({
						isShowPager:    false,
						slideCallback:  function(index) {
						    setIndex(index);
						}
					})
				}

				$body.delegate(picItem, 'click', function(event) {
					var $self = $(this);
					var result;
					if($self.index() == 0) {
						result = listData.house.images;
					} else {
						result = initIndexLeng(listData.house.rooms[$self.index()-1]);
					}
					$self.addClass("current").siblings().removeClass("current");
					// $picLen.text(result.length);
					reloadPic(result);
				});

				// init detail
				var itemTpl = util.renderItem('detail', listData.house)
				$mainList.append(itemTpl)

				// room
				var roomTpl = util.renderItem('room', listData.house)
				$mainList.append(roomTpl)

				if(listData.house.limits && listData.house.limits[0].code == 1) {
					$(mainOrder).remove();
				} else {
					util.getList(api_host + group_api_url, function(data) {
						var orderTpl = util.renderItem('order', {teams:data.teams, rooms: listData.house.rooms})
						$(mainOrder).append(orderTpl)
					});
				}
				
				// map
				function RectangleOverlay(mapPoint, label, className) {
				    this._mapPoint = mapPoint;
				    this._label = label;
				    this._className = className;
				}
				RectangleOverlay.prototype = new BMap.Overlay(); 
				RectangleOverlay.prototype.initialize = function(map) {
				    this._map = map;
				    this._overlayEl = document.createElement('div');
				    this._overlayEl.className = this._className;
				    this._overlayEl.style.zIndex = BMap.Overlay.getZIndex(this._mapPoint.lat);
				    this._labelEl = document.createElement('span');
				    this._labelEl.className = this._className + '-label';
				    this._labelEl.appendChild(document.createTextNode(this._label));
				    this._overlayEl.appendChild(this._labelEl);
				    this._map.getPanes().labelPane.appendChild(this._overlayEl);
				    return this._overlayEl;
				};

				RectangleOverlay.prototype.draw = function() {
				    var pixel = this._map.pointToOverlayPixel(this._mapPoint);
				    var style = window.getComputedStyle(this._overlayEl);
				    var overlayHeight = parseInt(style.height, 10);
				    this._overlayEl.style.left = pixel.x + 'px';
				    this._overlayEl.style.top = (pixel.y - overlayHeight) + 'px';
				};


				function handleNullMapData(point) {
					var map = new BMap.Map("container"); 
				    map.centerAndZoom(point, 16); 
				    // map
				    // var marker = new BMap.Marker(point);
				    // map.addOverlay(marker);
				    // var icon = new BMap.Icon('/app/static/weixin/img/location.png', new BMap.Size(12, 15));

				    // var mkr = new BMap.Marker(point , {
				    //     icon: icon
				    // });
				    // map.addOverlay(mkr);

				    var rectangleOverlay = new RectangleOverlay(point, listData.house.community, 'checkpoint-overlay');
				    map.addOverlay(rectangleOverlay);
				    

				    map.addControl(new BMap.ZoomControl());
				}
				if(!listData.house.gpsLng || !listData.house.gpsLat) {
						var myGeo = new BMap.Geocoder();
						
						myGeo.getPoint(listData.house.region + listData.house.community, function(point){
							if (point) {
								handleNullMapData(point);
							}
						}, '厦门市');
				} else {
					var point = new BMap.Point(listData.house.gpsLng, listData.house.gpsLat);
					handleNullMapData(point);
				}
				 

				util.getList(api_host + favorite_api_url, function(data) {
					console.log(data);
					var likeTpl = util.renderItem('like', {data: data, communityId: listData.house.communityId, limits: listData.house.limits})
					$mainList.append(likeTpl);
					function canWhole(data) {
						var bool = false;
						listData.house.limits.forEach(function(limit) {
							if(limit.code == 1) {
								bool = true;
							}
						})
						return bool
					}
					if(canWhole(listData.house.limits)) {
						
						var $body = $('body');
						var $fang = $('.zufang');
						var $mask  = $('.app-down-mask');
						var $related = $('.related');

						if(listData.house.contactMobile) {
							var html = '<a href="tel:' + listData.house.contactMobile + '">联系看房</a>'
							$related.html(html)
						}

						$fang.on('click', function(event) {
							$body.addClass('zufang');
						});
						$mask.on('click', function(event) {
							$body.removeClass('zufang');
						});
					}

				})

				wx.config({
				    debug: false,
				    appId: '<%= jsapiSignature.appId %>',
				    timestamp: "<%= jsapiSignature.timestamp %>",
				    nonceStr: '<%= jsapiSignature.noncestr %>',
				    signature: '<%= jsapiSignature.signature %>',
				    jsApiList: [
				        'onMenuShareTimeline',
				        'onMenuShareAppMessage'
				    ]
				});
				wx.ready(function(){

				    wx.onMenuShareTimeline({
				        title: '我发现了一间很棒的房源，快来合租吧~',
				        link: '',
				        imgUrl: '',
				        success: function () {

				        },
				        cancel: function () {
				            
				        }
				    });

				    wx.onMenuShareAppMessage({
				        title: '我发现了一间很棒的房源，快来合租吧~',
				        link: '',
				        desc: '我给您分享了一套房源哦~快来看看吧~ '+ listData.house.region + listData.house.roomNum +'室'+ listData.house.hallNum +'厅'+ listData.house.toiletNum +'卫'+ listData.house.area +'㎡',
				        imgUrl: '',
				        type: 'link',
				        dataUrl: '',
				        success: function () {

				        },
				        cancel: function () {
				            
				        }

				    });

				})

				
			})

		})();

	})
</script>
<% include ../partial/analyse %>
</html>
